"""
    Author:
    Date: 2019-03-08

    广播消息管理类
"""

from utils import db


def get_total_message_count():
    """ 获取广播的数量数量 """
    sql = '''
        SELECT      COUNT(*) AS total_count
        FROM        cmf_users_radio;
    '''
    data = db.query_data_from_db(sql)
    return data[0]['total_count'] if data else 0


def save_message(gm_id, category, uid, message, comment):
    """ 保存广播消息, 返回保存的message id """
    sql = '''
        INSERT INTO cmf_users_radio
        SET         gm_id=%(gm_id)s,
                    category=%(category)s,
                    uid=%(uid)s,
                    message=%(message)s,
                    comment=%(comment)s;
    '''
    params = {
        'gm_id': str(gm_id),
        'category': str(category),
        'uid': str(uid),
        'message': message,
        'comment': comment,
    }
    affected_rows = db.execute_sql(sql, params)
    if affected_rows == 1:
        return get_last_message_id()
    else:
        return 0


def get_last_message_id():
    """ 获取最后插入的记录的id """
    sql = '''
        SELECT  MAX(id) AS max_id
        FROM    cmf_users_radio;
    '''
    data = db.query_data_from_db(sql)
    return data[0]['max_id'] if data else 0


def get_message_logs(count):
    """ 获取广播消息日志 """
    sql = f'''
        SELECT      *
        FROM        cmf_users_radio
        ORDER BY    id DESC
        LIMIT       {count};
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


if __name__ == '__main__':
    print('ok')
